<?php
namespace Admin\Frontend\Controllers;

use Helpers\HttpException;
use Helpers\Tool;
use Helpers\Main;
use Helpers\User;
use Helpers\Cache;
use Helpers\Assets;
use Helpers\UserPower;
use Helpers\HttpClient;
use Modules\School;
use Phalcon\Db\Adapter\Pdo\Mysql;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\stats\XhstatsExamine;
use Services\BigData;

class StatsexamineController extends ControllerBase
{

    /**
     * @var HttpClient
     */
    public $httpClient;
    public $limitRecord     = false;    //true则限制单条记录分数上限
    public $filterExamine   = false;
    public $standard = [
        'cloudTask' => [
            'fix'       => 10,
            'group'     => 10,
            'wrong'     => 4,
            'courseware'=> 10,
            'recorrect' => 10,
            'score'     => 40
        ],
        'ztClass'   => [
            'valid'     => 10,
            'score'     => 10,
        ],
        'brush'     => [
            'maxScore'  => 60,
            'math'      => [
                'practice'  => 80,
                'score'     => 10
            ],
            'science'   => [
                'practice'  => 80,
                'score'     => 10
            ],
            'english'   => [
                'practice'  => 20,
                'score'     => 10
            ],
            'chinese'   => [
                'practice'  => 12,
                'score'     => 10
            ],
            'chineseColl' => [
                'practice'  => 12,
                'score'     => 10
            ]
        ],
        'speakTrain'    => [
            'fix'       => 10,
            'score'     => 10
        ],
        'chineseBasic'  => [
            'fix'       => 10,
            'score'     => 10
        ],
        'totalScore'    => 120
    ];
    public $devInfo  = [];
    public $tchInfo  = [];
    public $tchIds   = [];
    public $grades   = [];
    public $ignore   = [];

    public function initialize()
    {
        $this->httpClient = new HttpClient();
//        $this->httpClient->setTimeout(60);
    }

    /**
     * 考核页面
     *
     * @return \Phalcon\Mvc\View
     *
     * create by ck 20171028
     */
    public function indexAction()
    {
        $this->view->pick('statsexamine/index');
        Assets::select2('js/statsexamine/index.js');
        return $this->view->setVars([
            'viewAll'   => School::getPower() === true,
            'schoolArr' => User::getSchool(true),
            'power'     => [
                'refresh'   => UserPower::checkUserPower('Stats_Examine_Refresh'),
                'lock'      => UserPower::checkUserPower('Stats_Examine_Lock'),
            ]
        ]);
    }

    /**
     * 学校考核信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|\Phalcon\Mvc\View|string
     *
     * create by ck 20171028
     * modify by ck 20171116    缓存更改，分数上限规则更改
     * modify by ck 20171117    可根据时间获取
     * modify by ck 20180404    根据是否接口返回不同结果
     * modify by ck 20180425    当月数据可直接查询，可锁定记录
     * modify by ck 20180509    结构更改
     */
    public function infoAction()
    {
        $schoolId       = $this->request->getQuery('schoolId', 'int');
        $targetMonth    = $this->request->getQuery('targetMonth', 'string');
        $refresh        = $this->request->getQuery('refresh', 'string') == 'true';
        $lock           = $this->request->getQuery('lock', 'string') == 'true';
        $interface      = $this->request->getQuery('interface', 'string') == 'true';
        $startTime      = date('Y-m-01', strtotime($targetMonth));
        $endTime        = strtotime($startTime . ' +1 month');
        $startTime      = strtotime($startTime);
        $currentMonth   = date('Y-m') == $targetMonth;
        $limitTime      = strtotime(date('Y-m-d'));
        if ($endTime > $limitTime) {
            $endTime = $limitTime;
        }

        try {
            $statsModel = XhstatsExamine::findFirst([
                'conditions' => 'bDelete = 0 AND iSchoolId = :schoolId: AND sTargetMonth = :targetMonth:',
                'bind'       => ['schoolId' => $schoolId, 'targetMonth' => $targetMonth]
            ]);
            if (!$statsModel) {
                $statsModel = new XhstatsExamine([
                    'iSchoolId'     => $schoolId,
                    'sTargetMonth'  => $targetMonth,
                    'iStartTime'    => $startTime,
                    'iEndTime'      => $endTime,
                    'bLock'         => 0
                ]);
            }
            $this->filterExamine = true;
            if (!$refresh && $statsModel->mStatsInfo && $statsModel->iEndTime == $endTime) {
                $this->tchInfo  = $statsModel->mTchInfo;
                $this->tchIds   = array_keys($this->tchInfo);
                $statsInfo      = $statsModel->mStatsInfo;
                $gradeMode      = $statsModel->iMode == 2;
                $this->ignore   = $statsModel->mIgnore;
            } else {
                if (!$interface && !$currentMonth && !UserPower::checkUserPower('Stats_Examine_Refresh')) {
                    throw new \Exception('暂无数据，无刷新权限，请耐心等待');
                }
                if ($refresh && !$currentMonth && $statsModel->bLock && !User::isAdmin()) {
                    throw new \Exception('该记录已被锁定，不可刷新');
                }
                $this->tchInfo  = $this->getTchInfo($schoolId);
                $this->tchIds   = array_keys($this->tchInfo);
                $statsInfo      = $this->getStatsInfo($schoolId, $startTime, $endTime);
                $gradeMode      = XhschoolInfo::getExamineMode($schoolId) == 2;
                $statsModel->tCreateDate    = date('Y-m-d H:i:s');
                $statsModel->iCreateUserId  = User::getId();
            }
            $this->grades = array_unique(array_values($this->tchInfo));
            //获取忽略信息
            if ($this->request->getPost('ignore')) {
                if ($statsModel->bLock && !User::isAdmin()) {
                    throw new \Exception('该记录已锁定，不可重新计算');
                }
                $this->ignore = $this->getIgnoreList();
            }

            //各项得分计算
            $common         = $this->dealCommonScore($statsInfo['common'], $gradeMode);
            $math           = $this->dealBrushScore('math', $statsInfo['brush']['math'], $gradeMode);
            $science        = $this->dealBrushScore('science', $statsInfo['brush']['science'], $gradeMode);
            $english        = $this->dealBrushScore('english', $statsInfo['brush']['english'], $gradeMode);
            $chinese        = $this->dealBrushScore('chinese', $statsInfo['brush']['chinese'], $gradeMode);
            $chineseColl    = $this->dealBrushScore('chineseColl', $statsInfo['brush']['chineseColl'], $gradeMode);
            $speakTrain     = $this->dealSpeakTrainScore($statsInfo['speakTrain'], $gradeMode);
            $chineseBasic   = $this->dealChineseBasicScore($statsInfo['chineseBasic'], $gradeMode);

            //计算总分
            $brushScore = $math['avgScore']['total']
                + $science['avgScore']['total']
                + $english['avgScore']['total']
                + $chinese['avgScore']['total']
                + $chineseColl['avgScore']['total'];
            //刷题王上限
//            if ($brushScore > $this->standard['brush']['maxScore']) {
//                $brushScore = $this->standard['brush']['maxScore'];
//            }
            $finalScore = $common['avgScore']['total']
                + $brushScore
                + $speakTrain['avgScore']['total']
                + $chineseBasic['avgScore']['total'];

            //保存记录
            $statsModel->iScore          = $finalScore;
            $statsModel->iStartTime      = $startTime;
            $statsModel->iEndTime        = $endTime;
            $statsModel->iMode           = $gradeMode ? 2 : 1;
            $statsModel->mStatsInfo      = $statsInfo;
            $statsModel->mTchInfo        = $this->tchInfo;
            $statsModel->mIgnore         = $this->ignore;
            if ($lock) {
                $statsModel->bLock = 1;
            }
            if ($this->devInfo) {
                $statsModel->mDevInfo = $this->devInfo;
            }

            $viewVars = [
                'common'    => $common,
                'brush'     => [
                    'math'      => $math + ['name' => '题舟-数学'],
                    'science'   => $science + ['name' => '题舟-科学'],
                    'english'   => $english + ['name' => '题舟-英语'],
                    'chinese'   => $chinese + ['name' => '题舟-语文'],
                    'chineseColl'   => $chineseColl + ['name' => '题舟-文综'],
                ],
                'speakTrain'    => $speakTrain,
                'chineseBasic'  => $chineseBasic,
                'finalScore'    => $finalScore,
                'schoolName'    => $statsInfo['schoolName'],
                'targetTime'    => $statsInfo['targetTime'],
                'isLock'        => $statsModel->bLock
            ];

            //根据考核模式选择视图并计算各应用得分
            if ($gradeMode) {
                $this->view->pick('statsexamine/infoGrade');
                $viewVars['grades']     = $this->grades;
                $viewVars['gradeScore'] = [];
                $statsModel->mScoreInfo = [];
                foreach ($this->grades as $grade) {
                    $statsModel->mScoreInfo[$grade] = [];
                    $statsModel->mScoreInfo[$grade]['common']       = $common['avgScore'][$grade]['total'];
                    $statsModel->mScoreInfo[$grade]['mathBrush']    = $math['avgScore'][$grade]['total'];
                    $statsModel->mScoreInfo[$grade]['scienceBrush'] = $science['avgScore'][$grade]['total'];
                    $statsModel->mScoreInfo[$grade]['englishBrush'] = $english['avgScore'][$grade]['total'];
                    $statsModel->mScoreInfo[$grade]['chineseBrush'] = $chinese['avgScore'][$grade]['total'];
                    $statsModel->mScoreInfo[$grade]['chineseCollBrush'] = $chineseColl['avgScore'][$grade]['total'];
                    $statsModel->mScoreInfo[$grade]['speakTrain']   = $speakTrain['avgScore'][$grade]['total'];
                    $statsModel->mScoreInfo[$grade]['chineseBasic'] = $chineseBasic['avgScore'][$grade]['total'];
                    $viewVars['gradeScore'][$grade] = array_sum($statsModel->mScoreInfo[$grade]);
                }
            } else {
                $this->view->pick('statsexamine/info');
                $statsModel->mScoreInfo = [
                    'common'        => $common['avgScore']['total'],
                    'mathBrush'     => $math['avgScore']['total'],
                    'scienceBrush'  => $science['avgScore']['total'],
                    'englishBrush'  => $english['avgScore']['total'],
                    'chineseBrush'  => $chinese['avgScore']['total'],
                    'chineseCollBrush'  => $chineseColl['avgScore']['total'],
                    'speakTrain'    => $speakTrain['avgScore']['total'],
                    'chineseBasic'  => $chineseBasic['avgScore']['total']
                ];
            }
            $this->db->connect();
            if (!$statsModel->save()) {
                throw new \Exception($statsModel->getError());
            }
            $viewVars['createTime'] = $statsModel->tCreateDate;

            return $interface ? $this->sendSuccessResponse('成功') : $this->view->setVars($viewVars);
        } catch (\Exception $e) {
            return $interface
                ? $this->sendErrorResponse(500, $e->getMessage())
                : $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 获取学校考核应用使用情况
     *
     * @param $schoolId
     * @param $startTime
     * @param $endTime
     * @return array
     * @throws \Exception
     *
     * create by ck 20180508
     */
    public function getStatsInfo($schoolId, $startTime, $endTime)
    {
//        set_time_limit(0);
        ignore_user_abort(true);
        $limitTime = strtotime(date('Y-m-d'));
        if (!$schoolId || !$startTime || !$endTime) {
            throw new \Exception('缺少必要参数');
        }
        if ($startTime > $limitTime) {
            throw new \Exception('日期超出限制，不可查询');
        }
//        if (($endTime - $startTime) > 3600 * 24 * 31){
//            throw new \Exception('最多查询一个月数据');
//        }
        if ($endTime > $limitTime) {
            $endTime = $limitTime;
        }
        $config         = Main::getConfigByName('examine');
        $minValidTopic  = Tool::getValue($config, 'minValidTopic', 0);
//        $benefitScore   = Tool::getValue($config, 'benefitScore', 0);
//        $baseParams     = ['schoolId' => $schoolId, 'startTime' => $startTime, 'endTime' => $endTime];
        $data = [
            'common'    => $this->getCommonUsage($schoolId, $startTime, $endTime, $minValidTopic),
            'brush'     => [
                'math'      => $this->getBrushKingUsage(2, $schoolId, $startTime, $endTime),
                'science'   => $this->getBrushKingUsage('4,7,8,9,10', $schoolId, $startTime, $endTime),
                'english'   => $this->getBrushKingUsage(3, $schoolId, $startTime, $endTime),
                'chinese'   => $this->getBrushKingUsage(1, $schoolId, $startTime, $endTime),
                'chineseColl'=> $this->getBrushKingUsage('5,6,16', $schoolId, $startTime, $endTime),
//                'math'      => $this->getBrushAppUsage('Math', $baseParams, $benefitScore),
//                'science'   => $this->getBrushAppUsage('Science', $baseParams, $benefitScore),
//                'english'   => $this->getBrushAppUsage('English', $baseParams, $benefitScore),
//                'chinese'   => $this->getBrushAppUsage('Chinese', $baseParams, $benefitScore),
            ],
            'speakTrain'    => $this->getSpeakTrainUsage($schoolId, $startTime, $endTime),
            'chineseBasic'  => $this->getChineseBasicUsage($schoolId, $startTime, $endTime),
            'schoolName'    => School::getSchools()[$schoolId],
            'targetTime'    => date('Y-m-d', $startTime) . ' ~ '. date('Y-m-d', $endTime - 1)
        ];
        return $data;
    }

    /**
     * 获取有效教师列表及科目分组
     *
     * @param $schoolId
     * @return array
     *
     * create by ck 20180508
     * modify by ck 20180514    增加考核教师筛选
     */
    public function getTchInfo($schoolId)
    {
        $builder = $this->modelsManager->createBuilder()
            ->columns(['u.iUserId AS id', 't.iCurGrade AS grade'])
            ->from(['u' => '\\Admin\\Models\\user\\XhsysUser'])
            ->leftJoin('\\Admin\\Models\\sys\\XhsysUserTch', 'u.iUserId = t.iUserId', 't')
//            ->where('u.bDelete = 0 AND u.bCompany = 0 AND u.bDisable = 0 AND u.bHistory = 0')
            ->where('u.bDelete = 0 AND u.bDisable = 0 AND u.bHistory = 0')
            ->andWhere('u.iUserType = 4 AND u.iSchoolId = :schoolId:', ['schoolId' => $schoolId]);
        if ($this->filterExamine) {
            $builder->andWhere('t.iType = 1');       //计入考核教师
        }
        $data = $builder->getQuery()->execute()->toArray();
        $enum = XhsysEnum::getEnumByNodeName('年级');
//        $tchInfo = ['ids' => array_column($data, 'id')];
//        foreach ($data as $row) {
//            if (!isset($enum[$row['grade']])) {
//                continue;
//            }
//            $tchInfo['grade'][$enum[$row['grade']]][] = $row['id'];
//        }
        Tool::runEnum($data, ['grade' => $enum]);
        $tchInfo = array_column($data, 'grade', 'id');
        return $tchInfo;
    }

    /**
     * 获取学校考核信息
     *
     * @param null $schoolId
     * @param null $startTime
     * @param null $endTime
     * @return \Phalcon\Mvc\View|string
     * @throws \Exception
     *
     * create by ck 20171028
     * modify by ck 20171116    缓存更改，分数上限规则更改
     * modify by ck 20171117    可根据时间获取
     * modify by ck 20180404    根据是否接口返回不同结果
     * modify by ck 20180425    当月数据可直接查询，可锁定记录
     */
//    public function infoAction($schoolId = null, $startTime = null, $endTime = null)
//    {
//        set_time_limit(0);
//        ignore_user_abort(true);
//        $this->view->pick('statsexamine/info');
//        $schoolId       = $schoolId ?: $this->request->getQuery('schoolId', 'int');
//        $targetMonth    = $this->request->getQuery('targetMonth', 'string');
//        $refresh        = $this->request->getQuery('refresh', 'string') == 'true';
//        $lock           = $this->request->getQuery('lock', 'string') == 'true';
//        $interface      = $this->request->getQuery('interface', 'string') == 'true';
//        $limitTime      = strtotime(date('Y-m-d', time()));
//        $currentMonth   = false;
//        if ($targetMonth) {
//            $startTime      = date('Y-m-01', strtotime($targetMonth));
//            $endTime        = strtotime($startTime . ' +1 month');
//            $startTime      = strtotime($startTime);
//        }
//
//        $config         = Main::getConfigByName('examine');
//        $minValidTopic  = @$config['minValidTopic'] ?: 0;
//        $benefitScore   = @$config['benefitScore'] ?: 0;
//        try {
//            if (!$schoolId || !$startTime || !$endTime) {
//                throw new \Exception('缺少必要参数');
//            }
//            if ($startTime > $limitTime) {
//                throw new \Exception('日期超出限制，不可查询');
//            }
//            if (($endTime - $startTime) > 3600 * 24 * 31){
//                throw new \Exception('最多查询一个月数据');
//            }
//
//            if ($targetMonth) {
//                $statsModel = XhstatsExamine::findFirst([
//                    'conditions' => 'bDelete = 0 AND iSchoolId = :schoolId: AND sTargetMonth = :targetMonth:',
//                    'bind'       => ['schoolId' => $schoolId, 'targetMonth' => $targetMonth]
//                ]);
//            }
//
//            //如果结束时间大于限制时间，则统计到限制时间
//            if ($endTime > $limitTime) {
//                $endTime = $limitTime;
//                $currentMonth = true;
//            }
//
//            //有缓存则获取缓存
//            if ($targetMonth && !$refresh && isset($statsModel) && $statsModel && $statsModel->mStatsInfo && $statsModel->iEndTime == $endTime) {
//                $statsInfo = $statsModel->mStatsInfo;
//            }
//            else {
//                if ($targetMonth && !$interface && !$currentMonth && !UserPower::checkUserPower('Stats_Examine_Refresh')) {
//                    throw new \Exception('暂无数据，无刷新权限，请耐心等待');
//                }
//                if ($refresh && isset($statsModel) && $statsModel && $statsModel->bLock && !User::isAdmin()) {
//                    throw new \Exception('该记录已被锁定，不可刷新');
//                }
//                $baseParams = ['schoolId' => $schoolId, 'startTime' => $startTime, 'endTime' => $endTime];
//                $statsInfo  = [
//                    'common'    => $this->getCommonUsage($schoolId, $startTime, $endTime, $minValidTopic),
//                    'brush'     => [
//                        'math'      => $this->getBrushAppUsage('Math', $baseParams, $benefitScore),
//                        'science'   => $this->getBrushAppUsage('Science', $baseParams, $benefitScore),
//                        'english'   => $this->getBrushAppUsage('English', $baseParams, $benefitScore),
//                        'chinese'   => $this->getBrushAppUsage('Chinese', $baseParams, $benefitScore),
//                    ],
//                    'speakTrain'    => $this->getSpeakTrainUsage($schoolId, $startTime, $endTime),
//                    'chineseBasic'  => $this->getChineseBasicUsage($schoolId, $startTime, $endTime),
//                    'schoolName'    => XhschoolInfo::getSchoolSupportArray()[$schoolId],
//                    'targetTime'    => date('Y-m-d', $startTime) . ' ~ '. date('Y-m-d', $endTime - 1)
//                ];
//            }
//            if (!$targetMonth && !$interface) {
//                return $statsInfo;
//            }
//
//            //获取忽略信息
//            if ($this->request->getPost('ignore')) {
//                if (isset($statsModel) && $statsModel && $statsModel->bLock && !User::isAdmin()) {
//                    throw new \Exception('该记录已锁定，不可重新计算');
//                }
//                $statsInfo['ignore'] = $this->getIgnoreList();
//            }
//
//            //各项得分计算
//            $common         = $this->dealCommonScore($statsInfo['common'], @$statsInfo['ignore']['common']);
//            $math           = $this->dealBrushScore('Math', $statsInfo['brush']['math'], @$statsInfo['ignore']['mathBrush']);
//            $science        = $this->dealBrushScore('Science', $statsInfo['brush']['science'], @$statsInfo['ignore']['scienceBrush']);
//            $english        = $this->dealBrushScore('English', $statsInfo['brush']['english'], @$statsInfo['ignore']['englishBrush']);
//            $chinese        = $this->dealBrushScore('Chinese', $statsInfo['brush']['chinese'], @$statsInfo['ignore']['chineseBrush']);
//            $speakTrain     = $this->dealSpeakTrainScore($statsInfo['speakTrain'], @$statsInfo['ignore']['speakTrain']);
//            $chineseBasic   = $this->dealChineseBasicScore($statsInfo['chineseBasic'], @$statsInfo['ignore']['chineseBasic']);
//
//            //计算总分
//            $brushScore = $math['avgScore']['total']
//                + $science['avgScore']['total']
//                + $english['avgScore']['total']
//                + $chinese['avgScore']['total'];
//
//            //刷题王上限
////            if ($brushScore > $this->standard['brush']['maxScore']) {
////                $brushScore = $this->standard['brush']['maxScore'];
////            }
//            $finalScore = $common['avgScore']['total']
//                + $brushScore
//                + $speakTrain['avgScore']
//                + $chineseBasic['avgScore'];
//
//            $statsModel                  = isset($statsModel) && $statsModel ? $statsModel : new XhstatsExamine();
//            $statsModel->iSchoolId       = $schoolId;
//            $statsModel->sTargetMonth    = $targetMonth;
//            $statsModel->iStartTime      = $startTime;
//            $statsModel->iEndTime        = $endTime;
//            $statsModel->iScore          = $finalScore;
//            $statsModel->bLock           = $lock ? 1 : $statsModel->bLock;
//            $statsModel->mStatsInfo      = $statsInfo;
//            $statsModel->mScoreInfo      = [
//                'common'        => $common['avgScore']['total'],
//                'mathBrush'     => $math['avgScore']['total'],
//                'scienceBrush'  => $science['avgScore']['total'],
//                'englishBrush'  => $english['avgScore']['total'],
//                'chineseBrush'  => $chinese['avgScore']['total'],
//                'speakTrain'    => $speakTrain['avgScore'],
//                'chineseBasic'  => $chineseBasic['avgScore']
//            ];
//
//            if ($this->devInfo) {
//                $statsModel->mDevInfo = $this->devInfo;
//            }
//            $result = $statsModel->save();
//            if ($interface) {
//                return $result ? $this->sendSuccessResponse('成功') : $this->sendErrorResponse(500, $statsModel->getError());
//            }
//
//            return $this->view->setVars([
//                'common'    => $common,
//                'brush'     => [
//                    'math'      => $math + ['name' => '数学刷题王'],
//                    'science'   => $science + ['name' => '科学刷题王'],
//                    'english'   => $english + ['name' => '英语刷题王'],
//                    'chinese'   => $chinese + ['name' => '古文刷题王'],
//                ],
//                'speakTrain'    => $speakTrain,
//                'chineseBasic'  => $chineseBasic,
//                'finalScore'    => $finalScore,
//                'schoolName'    => $statsInfo['schoolName'],
//                'targetTime'    => $statsInfo['targetTime'],
//                'isLock'        => $statsModel->bLock
//            ]);
//        }
//        catch (\Exception $e) {
//            if ($interface) {
//                return $this->sendErrorResponse(500, $e->getMessage());
//            }
//            else if (!$targetMonth) {
//                throw new \Exception($e->getMessage());
//            }
//            else {
//                return $this->sendViewError($e->getMessage());
//            }
//        }
//    }

    /**
     * 获取需忽略列表
     *
     * @return array
     *
     * create by ck 20171102
     */
    private function getIgnoreList()
    {
        $ignore = [];
        foreach ($this->request->getPost() as $key => $value) {
            if (strpos($key, 'ignore_') === 0) {
                $key = str_replace('ignore_', '', $key);
                $ignore[$key] = $value;
            }
        }
        return $ignore;
    }

    /**
     * 获取通用应用信息
     *
     * @param $schoolId
     * @param $startTime
     * @param $endTime
     * @param int $minValidTopic
     * @return array
     *
     * create by ck 20171026
     */
    private function getCommonUsage($schoolId, $startTime, $endTime, $minValidTopic = 5)
    {
        $statsInfo  = [];
        $tchNum = 0;

        //云作业2.0
//        $time = microtime(true);
//        $cloudTask2 = $this->getCloudTask2($schoolId, $startTime, $endTime, $minValidTopic);
//        $this->devInfo['cloudTask2']['timeCost'] = microtime(true) - $time;
//        $this->devInfo['cloudTask2']['response'] = $cloudTask2;
        //云作业3.0
        $time = microtime(true);
        $cloudTask = $this->getHttpResult(
            'CA103001-3',
            '/intranet/work/statistic/school/teachers',
            ['schoolId' => $schoolId, 'startTime' => $startTime, 'endTime' => $endTime],
            ['minValidTopic' => $minValidTopic]
        );
        $this->devInfo['cloudTask3']['timeCost'] = microtime(true) - $time;
        $this->devInfo['cloudTask3']['response'] = $cloudTask;
        //合并云作业数据
//        $this->mergeCommonInfo($cloudTask, $cloudTask2);

        $this->filterStatsRecord($cloudTask, $schoolId);
        $this->dealClassList($cloudTask);

        //处理云作业数据
        $standard   = $this->standard['cloudTask'];
        foreach ($cloudTask as $info) {
            $tchId = $info['tchId'];
            $tchNum++;
            $statsInfo[$tchId] = [
                'tchId'     => $tchId,
                'tchName'   => $info['tchName'],
                'classNum'  => count($info['classList']),
                'classNames'=> array_column($info['classList'], 'className'),
                'stuNum'    => array_sum(array_column($info['classList'], 'stuNum')),
                'ztClass'   => [
                    'taskValidNum'      => 0,
                    'completeValidRate' => 0
                ]
            ];
            $record = [
                'taskFixNum'        => $info['taskFixNum'],
                'taskStuNum'        => $info['taskStuNum'],
                'taskUploadNum'     => $info['taskUploadNum'],
                'taskCorrectNum'    => $info['taskCorrectNum'],
                'avgTopicNum'       => $this->division($info['taskTopicNum'], $info['taskFixNum'], 2),
                'completeFixRate'   => $this->division($info['taskFixNum'], $standard['fix'], 2),
                'uploadRate'        => $this->division($info['taskUploadNum'], $info['taskStuNum'], 2),
                'correctRate'       => $this->division($info['taskCorrectNum'], $info['taskUploadNum'], 2),

                'taskGroupNum'      => $info['taskGroupNum'],
                'completeGroupRate' => $this->division($info['taskGroupNum'], $standard['group'], 2),

                'taskWrongNum'      => $info['taskWrongNum'],
                'completeWrongRate' => $this->division($info['taskWrongNum'], $standard['wrong'], 2),

                'coursewareNum'         => $info['coursewareNum'],
                'completeCoursewareRate'=> $this->division($info['coursewareNum'], $standard['courseware'], 2),

                'taskRecorrectNum'      => $info['taskRecorrectNum'],
                'completeRecorrectRate' => $this->division($info['taskRecorrectNum'], $standard['recorrect'], 2)
            ];
            $statsInfo[$tchId]['cloudTask'] = $record;
        }

        //智通课堂2.0
//        $time = microtime(true);
//        $ztClass2 = $this->getZtClass2($schoolId, $startTime, $endTime);
//        $this->devInfo['ztClass2']['timeCost'] = microtime(true) - $time;
//        $this->devInfo['ztClass2']['response'] = $ztClass2;

        //智通课堂3.X
        $time = microtime(true);
        $ztClass = $this->getHttpResult(
            'CA104001',
            sprintf('/api/v1/statistics/schools/%d/courses', $schoolId),
            ['startTime' => $startTime . '000', 'endTime' => $endTime . '000']
        );
        $this->devInfo['ztClassX']['timeCost'] = microtime(true) - $time;
        $this->devInfo['ztClassX']['response'] = $ztClass;

//        if (!$ztClass) {
//            //智通课堂3.0
//            $time = microtime(true);
//            $ztClass = $this->getHttpResult(
//                'CA104001-3',
//                'GM_TchReport',
//                ['schoolId' => $schoolId, 'startTime' => $startTime, 'endTime' => $endTime]
//            );
//            $this->devInfo['ztClass3']['timeCost'] = microtime(true) - $time;
//            $this->devInfo['ztClass3']['response'] = $ztClass;
//        }


        //合并课堂数据
//        $this->mergeCommonInfo($ztClass, $ztClass2);
        $this->filterStatsRecord($ztClass, $schoolId);

        //处理智通课堂数据
        $standard   = $this->standard['ztClass'];
        foreach ($ztClass as $info) {
            $tchId = $info['tchId'];
            if (!isset($statsInfo[$tchId])) {
                $statsInfo[$tchId] = [
                    'tchId'     => $tchId,
                    'tchName'   => $info['tchName'],
                    'classNum'  => count($info['classList']),
                    'classNames'=> array_column($info['classList'], 'className'),
                    'stuNum'    => array_sum(array_column($info['classList'], 'stuNum')),
                    'cloudTask' => [
                        'taskFixNum'        => 0,
                        'avgTopicNum'       => 0,
                        'completeFixRate'   => 0,
                        'uploadRate'        => 0,
                        'correctRate'       => 0,
                        'taskGroupNum'      => 0,
                        'completeGroupRate' => 0,
                        'taskWrongNum'      => 0,
                        'completeWrongRate' => 0,
                        'coursewareNum'         => 0,
                        'completeCoursewareRate'=> 0,
                        'taskRecorrectNum'      => 0,
                        'completeRecorrectRate' => 0,
                    ]
                ];
                $tchNum++;
            }
            $record = [
                'taskValidNum'      => $info['taskValidNum'],
                'completeValidRate' => $this->division($info['taskValidNum'], $standard['valid'], 2)
            ];
            $statsInfo[$tchId]['ztClass'] = $record;
        }

        return array_values($statsInfo);
    }

    /**
     * 处理通用应用得分
     *
     * @param $statsInfo
     * @param $gradeMode
     * @return array
     *
     * create by ck 20171102
     * modify by ck 20171116    云作业，智通课堂设置上限
     * modify by ck 20180509    可根据科目分类
     */
    private function dealCommonScore(&$statsInfo, $gradeMode = false)
    {
        //初始化数据
        $ignoreIds = Tool::getValue($this->ignore, 'common', []);
        $cloudStandard  = $this->standard['cloudTask'];
        $cloudBaseScore = $cloudStandard['score'];
        $cloudExtraScore= $cloudBaseScore * 0.2;

        $classStandard  = $this->standard['ztClass'];
        $classBaseScore = $classStandard['score'];

        //处理单条得分
        foreach ($statsInfo as $index => &$record) {
            //去除非正常数据
//            if (!in_array($record['tchId'], $this->tchIds)) {
//                unset($statsInfo[$index]);
//                continue;
//            }

            //云作业
            $record['cloudTask']['scoreBase'] = $this->dealRound(
                $cloudBaseScore
                * $record['cloudTask']['completeFixRate']
                * $record['cloudTask']['uploadRate']
                * $record['cloudTask']['correctRate'],
                1
            );
            $record['cloudTask']['scoreExtra'] = $this->dealRound(
                $cloudExtraScore * $record['cloudTask']['completeGroupRate']
                + $cloudExtraScore * $record['cloudTask']['completeWrongRate']
                + $cloudExtraScore * $record['cloudTask']['completeCoursewareRate']
                + $cloudExtraScore * $record['cloudTask']['completeRecorrectRate'],
                1
            );
            if ($this->limitRecord && $record['cloudTask']['scoreBase'] > $cloudBaseScore) {
                $record['cloudTask']['scoreBase'] = $cloudBaseScore;
            }
            if ($this->limitRecord && $record['cloudTask']['scoreExtra'] > $cloudExtraScore) {
                $record['cloudTask']['scoreExtra'] = $cloudExtraScore;
            }
            $record['cloudTask']['score'] = $record['cloudTask']['scoreBase'] + $record['cloudTask']['scoreExtra'];

            //智通课堂
            $record['ztClass']['score']  = $this->dealRound(
                $classBaseScore * $record['ztClass']['completeValidRate'],
                1
            );
            if ($this->limitRecord && $record['ztClass']['score'] > $classBaseScore) {
                $record['ztClass']['score'] = $classBaseScore;
            }

            //处理忽略
            @$record['score'] = $record['cloudTask']['score'] + $record['ztClass']['score'];
            $record['ignore'] = in_array($record['tchId'], $ignoreIds);
        }
        unset($record);

        //计算总分
        if (!$gradeMode) {
            $totalScore = ['cloudTask' => 0, 'ztClass' => 0, 'total' => 0];
            $tchNum     = 0;
            foreach ($statsInfo as $record) {
                if ($record['ignore']) {
                    continue;
                }
                $totalScore['cloudTask'] += $record['cloudTask']['score'];
                $totalScore['ztClass']   += $record['ztClass']['score'];
                $tchNum++;
            }

            $cloudAvgScore  = $this->division($totalScore['cloudTask'], $tchNum, 1);
            $classAvgScore  = $this->division($totalScore['ztClass'], $tchNum, 1);

            //上限
            if ($cloudAvgScore > ($cloudBaseScore + $cloudExtraScore)) {
                $cloudAvgScore = $cloudBaseScore + $cloudExtraScore;
            }
            if ($classAvgScore > $classBaseScore) {
                $classAvgScore = $classBaseScore;
            }

            return [
                'rows'     => $statsInfo,
                'standard' => [
                    'cloudTask' => $this->standard['cloudTask'],
                    'ztClass'   => $this->standard['ztClass'],
                ],
                'avgScore' => [
                    'cloudTask' => $cloudAvgScore,
                    'ztClass'   => $classAvgScore,
                    'total'     => $cloudAvgScore + $classAvgScore
                ]
            ];
        } else {
            $gradeStatsInfo = $totalScore = $tchNum = [];
            foreach ($this->grades as $grade) {
                $gradeStatsInfo[$grade] = [];
                $clazzIds[$grade] = [];
            }
            foreach ($statsInfo as $record) {
                $grade = Tool::getValue($this->tchInfo, $record['tchId'], '未知年级');
                $gradeStatsInfo[$grade][] = $record;
                if ($record['ignore']) {
                    continue;
                }
                @$totalScore[$grade]['cloudTask'] += $record['cloudTask']['score'];
                @$totalScore[$grade]['ztClass']   += $record['ztClass']['score'];
                @$tchNum[$grade]++;
            }

            $result = [
                'rows'     => $gradeStatsInfo,
                'standard' => [
                    'cloudTask' => $this->standard['cloudTask'],
                    'ztClass'   => $this->standard['ztClass'],
                ],
                'avgScore' => [],
            ];
            $finalScore = 0;
            foreach ($this->grades as $grade) {
                $cloudAvgScore  = $this->division($totalScore[$grade]['cloudTask'], $tchNum[$grade], 1);
                $classAvgScore  = $this->division($totalScore[$grade]['ztClass'], $tchNum[$grade], 1);

                //上限
                if ($cloudAvgScore > ($cloudBaseScore + $cloudExtraScore)) {
                    $cloudAvgScore = $cloudBaseScore + $cloudExtraScore;
                }
                if ($classAvgScore > $classBaseScore) {
                    $classAvgScore = $classBaseScore;
                }
                $result['avgScore'][$grade] = [
                    'cloudTask' => $cloudAvgScore,
                    'ztClass'   => $classAvgScore,
                    'total'     => $cloudAvgScore + $classAvgScore
                ];
                $finalScore += $result['avgScore'][$grade]['total'];
            }
            $result['avgScore']['total'] = $this->division($finalScore, count($this->grades), 1);
            return $result;
        }
    }

    /**
     * 获取学海题舟数据
     *
     * @param $subjectId
     * @param $schoolId
     * @param $startTime
     * @param $endTime
     * @return array
     *
     * create by ck 20181018
     */
    private function getBrushKingUsage($subjectId, $schoolId, $startTime, $endTime)
    {
        $time = microtime(true);
        $brushInfo = BigData::getSubjectKpiInfo($subjectId, $schoolId, $startTime, $endTime);
        $this->devInfo['Brush_' . $subjectId]['timeCost'] = microtime(true) - $time;
        $this->devInfo['Brush_' . $subjectId]['response'] = $brushInfo;
        $this->filterStatsRecord($brushInfo, $schoolId);

        $statsInfo = [];
        foreach ($brushInfo as $info) {
            $record = [
                'classId'       => $info['classId'],
                'className'     => $info['className'],
                'tchId'         => $info['tchId'],
                'tchName'       => $info['tchName'],
                'practiceNum'   => $this->division($info['practiceNum'], $info['stuNum'], 2),
                'taskFixNum'    => $info['taskFixNum'],
                'uploadRate'    => $this->division($info['taskUploadNum'], $info['taskStuNum'], 2),
            ];
            $statsInfo[] = $record;
        }
        $this->mergeClassInfo($statsInfo);
        return $statsInfo;
    }

    /**
     * 获取刷题王系列应用信息
     *
     * @param $subjectName
     * @param $baseParams
     * @param $extraParam
     * @return array
     *
     * create by ck 20171027
     */
//    private function getBrushAppUsage($subjectName, $baseParams, $extraParam)
//    {
//        $statsInfo = [];
//        $time      = microtime(true);
//        $funName   = 'get' . ucfirst($subjectName) . 'Brush';
//        $brushInfo = $this->$funName($baseParams['schoolId'], $baseParams['startTime'], $baseParams['endTime'], $extraParam);
//        $this->filterStatsRecord($brushInfo, $baseParams['schoolId']);
//        $this->devInfo[strtolower($subjectName) . 'Brush']['timeCost'] = microtime(true) - $time;
//        $this->devInfo[strtolower($subjectName) . 'Brush']['response'] = $brushInfo;
//        foreach ($brushInfo as $info) {
//            $record = [
//                'classId'       => $info['classId'],
//                'className'     => $info['className'],
//                'tchId'         => $info['tchId'],
//                'tchName'       => $info['tchName'],
//                'practiceNum'   => $this->division($info['practiceNum'], $info['stuNum'], 2),
//                'taskFixNum'    => $info['taskFixNum'],
//                'uploadRate'    => $this->division($info['taskUploadNum'], $info['taskStuNum'], 2),
//            ];
//            $statsInfo[] = $record;
//        }
//        $this->mergeClassInfo($statsInfo);
//        return $statsInfo;
//    }

    /**
     * 处理刷题应用得分
     *
     * @param $subjectName
     * @param $statsInfo
     * @param $gradeMode
     * @return array
     *
     * create by ck 20171102
     * modify by ck 20180509     可根据科目分类
     */
    private function dealBrushScore($subjectName, &$statsInfo, $gradeMode = false)
    {
        $ignoreIds = Tool::getValue($this->ignore, $subjectName . 'Brush', []);
        $standard  = $this->standard['brush'][$subjectName];
        $baseScore = $standard['score'];

        foreach ($statsInfo as &$record) {
            $record['scoreBase']  = $this->dealRound(
                $baseScore
                * ($this->division($record['practiceNum'], $standard['practice'])),
                1
            );
            $record['scoreExtra'] = $this->dealRound($record['taskFixNum'] * $record['uploadRate'], 1);
            if ($this->limitRecord && $record['scoreBase'] > $baseScore) {
                $record['scoreBase'] = $baseScore;
            }

            //处理忽略
            $record['ignore'] = in_array($record['classId'], $ignoreIds);
        }
        unset($record);

        //计算总分
        if (!$gradeMode) {
            $totalScore = ['scoreBase' => 0, 'scoreExtra' => 0];
            $classNum   = 0;
            $clazzIds   = [];
            foreach ($statsInfo as $record) {
                if ($record['ignore']) {
                    continue;
                }
                $totalScore['scoreBase']  += $record['scoreBase'];
                $totalScore['scoreExtra'] += $record['scoreExtra'];
                if (!in_array($record['clazzId'], $clazzIds)) {
                    $clazzIds[] = $record['clazzId'];
                    $classNum++;
                }
            }

            $baseAvgScore  = $this->division($totalScore['scoreBase'], $classNum, 1);
            $extraAvgScore = $this->division($totalScore['scoreExtra'], $classNum, 1);

            //上限
            if ($baseAvgScore > $baseScore) {
                $baseAvgScore = $baseScore;
            }
            $total = $this->dealRound($baseAvgScore + $extraAvgScore, 1);
            //双重上限
            if ($total > $baseScore) {
                $total = $baseScore;
            }

            return [
                'rows'     => $statsInfo,
                'standard' => $standard,
                'avgScore' => [
                    'base'  => $baseAvgScore,
                    'extra' => $extraAvgScore,
                    'total' => $total
                ]
            ];
        } else {
            $gradeStatsInfo = $totalScore = $classNum = $clazzIds = [];
            foreach ($this->grades as $grade) {
                $gradeStatsInfo[$grade] = [];
                $clazzIds[$grade] = [];
            }
            foreach ($statsInfo as $record) {
                $grade = Tool::getValue($this->tchInfo, $record['tchId'], '未知年级');
                $gradeStatsInfo[$grade][] = $record;
                if ($record['ignore']) {
                    continue;
                }
                @$totalScore[$grade]['scoreBase']    += $record['scoreBase'];
                @$totalScore[$grade]['scoreExtra']   += $record['scoreExtra'];
                if (!in_array($record['clazzId'], $clazzIds[$grade])) {
                    @$clazzIds[$grade][] = $record['clazzId'];
                    @$classNum[$grade]++;
                }
            }

            $result = [
                'rows'     => $gradeStatsInfo,
                'standard' => $standard,
                'avgScore' => [],
            ];
            $finalScore = 0;
            foreach ($this->grades as $grade) {
                $baseAvgScore   = isset($totalScore[$grade])
                    ? $this->division($totalScore[$grade]['scoreBase'], $classNum[$grade], 1)
                    : 0;
                $extraAvgScore  = isset($totalScore[$grade])
                    ? $this->division($totalScore[$grade]['scoreExtra'], $classNum[$grade], 1)
                    : 0;

                //上限
                if ($baseAvgScore > $baseScore) {
                    $baseAvgScore = $baseScore;
                }
                $total = $this->dealRound($baseAvgScore + $extraAvgScore, 1);
                //双重上限
                if ($total > $baseScore) {
                    $total = $baseScore;
                }

                $result['avgScore'][$grade] = [
                    'base'  => $baseAvgScore,
                    'extra' => $extraAvgScore,
                    'total' => $total
                ];
                $finalScore += $result['avgScore'][$grade]['total'];
            }
            $result['avgScore']['total'] = $this->division($finalScore, count($this->grades), 1);
            return $result;
        }
    }

    /**
     * 获取口语训练应用信息
     *
     * @param $schoolId
     * @param $startTime
     * @param $endTime
     * @return array
     * @throws HttpException
     *
     * create by ck 20171028
     * modify by ck 20180504    添加自建班标识
     * modify by sqb 20190102   添加云听说数据
     */
    private function getSpeakTrainUsage($schoolId, $startTime, $endTime)
    {
        $statsInfo  = [];
        $time       = microtime(true);
        $speakTrain = $this->getSpeakTrain($schoolId, $startTime, $endTime);
        $this->filterStatsRecord($speakTrain, $schoolId);
        $this->devInfo['speakTrain']['timeCost'] = microtime(true) - $time;
        $this->devInfo['speakTrain']['response'] = $speakTrain;

        //添加云听说数据
        try {
            $hear = BigData::getHearKpiInfo($schoolId, $startTime, $endTime);
        } catch (\Exception $e) {
            throw new HttpException('云听说数据获取失败', $e->getMessage());
        }

        foreach ($hear as &$item) {
            $item['id'] = $item['classId'].'_'.$item['teacherId'];
        }
        $hear = array_column($hear, null, 'id');

        foreach ($speakTrain as $info) {
            //添加云听说数据
            $taskFixNum = $info['taskFixNum'];
            $id = $info['classId'].'_'.$info['tchId'];
            if ($hear && $hear[$id]) {
                $taskFixNum += $hear[$id]['assignHomeworkNum'];
            }

            $record = [
                'classId'       => $info['classId'],
                'className'     => $info['className'],
                'tchId'         => $info['tchId'],
                'tchName'       => $info['tchName'],
                'taskFixNum'    => $taskFixNum,
                'clazz'         => $info['clazz']
            ];
            $statsInfo[] = $record;
        }
        $this->mergeClassInfo($statsInfo);
        $speakIds = array_column($statsInfo, 'classId');
        $hearIds = array_keys($hear);
        $diffIds = array_diff($hearIds, $speakIds);
        if ($diffIds) {
            foreach ($diffIds as $diffId) {
                $statsInfo[] = [
                    'classId' => $diffId,
                    'className' => $hear[$diffId]['className'],
                    'tchId' => $hear[$diffId]['teacherId'],
                    'tchName' => $hear[$diffId]['teacherName'],
                    'taskFixNum' => $hear[$diffId]['assignHomeworkNum'],
                    'clazzId' => $hear[$diffId]['classId']
                ];
            }
        }

        return $statsInfo;
    }

    /**
     * 处理口语训练得分
     *
     * @param $statsInfo
     * @param $gradeMode
     * @return array
     *
     * create by ck 20171102
     * modify by ck 20180504    忽略自建班得分
     * modify by ck 20180509    可根据科目分类
     */
    private function dealSpeakTrainScore(&$statsInfo, $gradeMode = false)
    {
        $ignoreIds = Tool::getValue($this->ignore, 'speakTrain' , []);
        $standard  = $this->standard['speakTrain'];
        $baseScore = $standard['score'];

        foreach ($statsInfo as &$record) {
            $record['score'] = $this->dealRound(
                $baseScore
                * ($this->division($record['taskFixNum'], $standard['fix'])),
                1
            );
            if ($this->limitRecord && $record['score'] > $baseScore) {
                $record['score'] = $baseScore;
            }
            $record['ignore'] = in_array($record['classId'], $ignoreIds);
        }
        unset($record);

        //计算总分
        if (!$gradeMode) {
            $totalScore = $classNum   = 0;
            $clazzIds   = [];
            foreach ($statsInfo as $record) {
                if ($record['ignore']) {
                    continue;
                }
                $totalScore += $record['score'];

                //忽略自建班基数
                if ($record['clazz']) {
                    if (!in_array($record['clazzId'], $clazzIds)) {
                        $clazzIds[] = $record['clazzId'];
                        $classNum++;
                    }
                } else {
                    $record['className'] = '<i>' . $record['className'] . '</i>';
                }
            }
            $avgScore = $this->division($totalScore, $classNum, 1);

            //上限
            if ($avgScore > $standard['score']) {
                $avgScore = $standard['score'];
            }
            return [
                'rows'     => $statsInfo,
                'standard' => $standard,
                'avgScore' => ['total' => $avgScore]
            ];
        }
        else {
            $gradeStatsInfo = $totalScore = $classNum = $clazzIds = [];
            foreach ($this->grades as $grade) {
                $gradeStatsInfo[$grade] = [];
                $clazzIds[$grade] = [];
            }
            foreach ($statsInfo as $record) {
                $grade = Tool::getValue($this->tchInfo, $record['tchId'], '未知年级');
                $gradeStatsInfo[$grade][] = $record;
                if ($record['ignore']) {
                    continue;
                }
                @$totalScore[$grade] += $record['score'];

                //忽略自建班基数
                if ($record['clazz']) {
                    if (!in_array($record['clazzId'], $clazzIds[$grade])) {
                        @$clazzIds[$grade][] = $record['clazzId'];
                        @$classNum[$grade]++;
                    }
                } else {
                    $record['className'] = '<i>' . $record['className'] . '</i>';
                }
            }

            $result = [
                'rows'     => $gradeStatsInfo,
                'standard' => $standard,
                'avgScore' => [],
            ];
            $finalScore = 0;
            foreach ($this->grades as $grade) {
                $avgScore = $this->division($totalScore[$grade], $classNum[$grade], 1) ?: 0;

                //上限
                if ($avgScore > $standard['score']) {
                    $avgScore = $standard['score'];
                }

                $result['avgScore'][$grade]['total'] = $avgScore;
                $finalScore += $avgScore;
            }
            $result['avgScore']['total'] = $this->division($finalScore, count($this->grades), 1);
            return $result;
        }
    }

    /**
     * 获取语文基础知识应用信息
     *
     * @param $schoolId
     * @param $startTime
     * @param $endTime
     * @return array
     *
     * create by ck 20171028
     * modify by ck 20180504    添加自建班标识
     */
    private function getChineseBasicUsage($schoolId, $startTime, $endTime)
    {
        $statsInfo    = [];
        $time         = microtime(true);
        $chineseBasic = $this->getChineseBasic($schoolId, $startTime, $endTime);
        $this->filterStatsRecord($chineseBasic, $schoolId);
        $this->devInfo['chineseBasic']['timeCost'] = microtime(true) - $time;
        $this->devInfo['chineseBasic']['response'] = $chineseBasic;
        foreach ($chineseBasic as $info) {
            $record = [
                'classId'       => $info['classId'],
                'className'     => $info['className'],
                'tchId'         => $info['tchId'],
                'tchName'       => $info['tchName'],
                'taskFixNum'    => $info['taskFixNum'],
                'clazz'         => $info['clazz'],
            ];
            $statsInfo[] = $record;
        }
        $this->mergeClassInfo($statsInfo);
        return $statsInfo;
    }

    /**
     * 处理语文基础知识得分
     *
     * @param $statsInfo
     * @param $gradeMode
     * @return array
     *
     * create by ck 20171102
     * modify by ck 20180504    忽略自建班得分
     * modify by ck 20180509    根据科目分类
     */
    private function dealChineseBasicScore(&$statsInfo, $gradeMode = false)
    {
        $ignoreIds = Tool::getValue($this->ignore, 'chineseBasic' , []);
        $standard  = $this->standard['chineseBasic'];
        $baseScore = $standard['score'];

        foreach ($statsInfo as &$record) {
            $record['score'] = $this->dealRound(
                $baseScore
                * ($this->division($record['taskFixNum'], $standard['fix'])),
                1
            );
            if ($this->limitRecord && $record['score'] > $baseScore) {
                $record['score'] = $baseScore;
            }
            $record['ignore'] = in_array($record['classId'], $ignoreIds);
        }
        unset($record);

        //计算总分
        if (!$gradeMode) {
            $totalScore = $classNum = 0;
            $clazzIds   = [];
            foreach ($statsInfo as $record) {
                if ($record['ignore']) {
                    continue;
                }
                $totalScore += $record['score'];

                //忽略自建班基数
                if ($record['clazz']) {
                    if (!in_array($record['clazzId'], $clazzIds)) {
                        $clazzIds[] = $record['clazzId'];
                        $classNum++;
                    }
                } else {
                    $record['className'] = '<i>' . $record['className'] . '</i>';
                }
            }
            $avgScore = $this->division($totalScore, $classNum, 1);

            //上限
            if ($avgScore > $standard['score']) {
                $avgScore = $standard['score'];
            }
            return [
                'rows'     => $statsInfo,
                'standard' => $standard,
                'avgScore' => ['total' => $avgScore]
            ];
        }
        else {
            $gradeStatsInfo = $totalScore = $classNum = $clazzIds = [];
            foreach ($this->grades as $grade) {
                $gradeStatsInfo[$grade] = [];
                $clazzIds[$grade] = [];
            }
            foreach ($statsInfo as $record) {
                $grade = Tool::getValue($this->tchInfo, $record['tchId'], '未知年级');
                $gradeStatsInfo[$grade][] = $record;
                if ($record['ignore']) {
                    continue;
                }
                @$totalScore[$grade] += $record['score'];

                //忽略自建班基数
                if ($record['clazz']) {
                    if (!in_array($record['clazzId'], $clazzIds[$grade])) {
                        @$clazzIds[$grade][] = $record['clazzId'];
                        @$classNum[$grade]++;
                    }
                } else {
                    $record['className'] = '<i>' . $record['className'] . '</i>';
                }
            }

            $result = [
                'rows'     => $gradeStatsInfo,
                'standard' => $standard,
                'avgScore' => [],
            ];
            $finalScore = 0;
            foreach ($this->grades as $grade) {
                $avgScore = $this->division($totalScore[$grade], $classNum[$grade], 1) ?: 0;

                //上限
                if ($avgScore > $standard['score']) {
                    $avgScore = $standard['score'];
                }

                $result['avgScore'][$grade]['total'] = $avgScore;
                $finalScore += $avgScore;
            }
            $result['avgScore']['total'] = $this->division($finalScore, count($this->grades), 1);
            return $result;
        }
    }

    /**
     * 获取云作业2.0考核表所需统计信息
     *
     * @param $schoolId
     * @param $startTime
     * @param $endTime
     * @param int $minValidTopic
     * @return array
     * @throws \Exception
     *
     * create by ck 20171025
     */
//    private function getCloudTask2($schoolId, $startTime, $endTime, $minValidTopic = 5)
//    {
//        $startTime = date('Y-m-d H:i:s', $startTime);
//        $endTime   = date('Y-m-d H:i:s', $endTime);
//        $dbName    = '';
//        $conn      = Main::getSchoolMainDB($schoolId, $dbName);
//        if (!$conn) {
//            throw new \Exception('数据库连接失败');
//        }
//        $tchInfo = [];
////        $collList = $conn->fetchAll("SELECT co_id, co_dates, group_concat(cl_id) as cl_ids, te_us_id, ( SELECT us_name FROM users WHERE us_id = te_us_id ) AS te_us_name, sy_name, at_qc_id FROM attendclass_time_class, teacher_list, course_list, class_list, system_type, users WHERE cl_at_id = at_id AND co_id = te_co_id AND te_us_id = us_id AND us_xk_flag = 0 AND te_flag = 0 AND cl_flag = 1 AND cl_id = te_cl_id AND co_coach_flag = 0 AND co_typeflag = 1 AND co_km_id = sy_id AND at_qc_id IN ( SELECT sy_id FROM system_type WHERE sy_type = 'kkqcsz' AND sy_state = 0 AND sy_name2 = 1 ) and co_status = 1 GROUP BY co_id, te_us_id ORDER BY co_ord");
//        $collList = $conn->fetchAll("SELECT co_id, co_dates, group_concat(cl_id) as cl_ids, te_us_id, ( SELECT us_name FROM users WHERE us_id = te_us_id ) AS te_us_name, sy_name, at_qc_id FROM attendclass_time_class, teacher_list, course_list, class_list, system_type, users WHERE cl_at_id = at_id AND co_id = te_co_id AND te_us_id = us_id AND us_xk_flag = 0 AND te_flag = 0 AND cl_flag = 1 AND cl_id = te_cl_id AND co_coach_flag = 0 AND co_typeflag = 1 AND co_km_id = sy_id AND at_qc_id IN ( SELECT sy_id FROM system_type WHERE sy_type = 'kkqcsz' AND sy_state = 0) and co_status = 1 GROUP BY co_id, te_us_id ORDER BY co_ord");
//        foreach ($collList as $coll) {
//            $tchId = $coll['te_us_id'];
//            if (!isset($tchInfo[$tchId])) {
//                $tchInfo[$tchId] = [
//                    'tchId'             => $tchId,
//                    'tchName'           => $coll['te_us_name'],
//                    'classList'         => [],
//                    'taskFixNum'        => 0,
//                    'taskTopicNum'      => 0,
//                    'taskStuNum'        => 0,
//                    'taskUploadNum'     => 0,
//                    'taskCorrectNum'    => 0,
//                    'taskGroupNum'      => 0,
//                    'taskWrongNum'      => 0,
//                    'coursewareNum'     => 0,
//                    'taskRecorrectNum'  => 0
//                ];
//            }
//            $dbCourse = $dbName . '_course' . $coll['co_id'];
//
//            try {
//                //获取班级信息
////                $class = $conn->fetchOne("select cl_id as classId,cl_name as className from class_list where cl_id = {$coll['cl_id']}");
////                $stuNum = $conn->fetchOne("select count(*) as stuNum from students_list where st_cl_id = {$coll['cl_id']}")['stuNum'];
////                $tchInfo[$tchId]['classList'][] = array_merge($class, ['stuNum' => $stuNum, 'coId' => $coll['co_id']]);
//                $tchInfo[$tchId]['classList'] = $conn->fetchAll("select cl_id as classId,cl_name as className,cl_co_id as coId,count(st_us_id) as stuNum from class_list,students_list where cl_id = st_cl_id and cl_id in ({$coll['cl_ids']}) group by cl_id");
//
//                //获取作业id/是否错题/题量
//                $sql = "SELECT le_id,le_wrong_flag,count(lh_id) AS lh_count FROM {$dbCourse}.lesson_course LEFT JOIN {$dbCourse}.lesson_homework_list ON le_id = lh_le_id AND lh_ho_parent_id = 0 WHERE le_tmpflag = 0 AND le_us_id = '{$tchId}' and le_dates >= '{$startTime}' and le_dates < '{$endTime}' GROUP BY le_id HAVING lh_count >= {$minValidTopic}";
//                $taskList = $conn->fetchAll($sql);
//                if (!$taskList) {
//                    continue;
//                }
//                $taskIds = [];
//                foreach ($taskList as $task) {
//                    $taskIds[] = $task['le_id'];
//
//                    $tchInfo[$tchId]['taskFixNum']++;
//                    $tchInfo[$tchId]['taskTopicNum'] += $task['lh_count'];
//                    if ($task['le_wrong_flag']) {
//                        $tchInfo[$tchId]['taskWrongNum']++;
//                    }
//                }
//                $taskIds = implode(',', $taskIds);
//
//                //获取作业分组布置次数
//                $groupNum = $conn->fetchOne("select count(*) as count from {$dbCourse}.object_student_homework where ob_flag = 1 and ob_zb_id > 0 and ob_le_id in ({$taskIds})")['count'];
//                $tchInfo[$tchId]['taskGroupNum'] += $groupNum;
//
//                //获取作业布置份份数
//                $taskStuNum = $conn->fetchOne("select count(*) as count from {$dbCourse}.object_student_homework,students_list where st_co_id='{$coll['co_id']}' and ob_us_id=st_us_id and ob_flag=0 and ob_le_id in ({$taskIds})")['count'];
//                $tchInfo[$tchId]['taskStuNum'] += $taskStuNum;
//
//                //获取作业上交份数
//                $taskUploadNum = $conn->fetchOne("select count(*) as count from {$dbCourse}.operation_student where op_le_id in ({$taskIds})")['count'];
//                $tchInfo[$tchId]['taskUploadNum'] += $taskUploadNum;
//
//                //获取作业批改份数
//                $taskCorrectNum = $conn->fetchOne("select count(*) as count from {$dbCourse}.operation_student where op_zypg_flag = 1 and op_le_id in ({$taskIds})")['count'];
//                $tchInfo[$tchId]['taskCorrectNum'] += $taskCorrectNum;
//
//                //获取二次批改次数（通过/有笔迹，暂不统计点击重订情况）
//                $recorrectArr1 = $conn->fetchAll("SELECT DISTINCT(an_le_id) as le_id FROM {$dbCourse}.answer_student_homework_base where an_glt_dispflag = 1 and an_le_id in ({$taskIds})");
//                $recorrectArr1 = array_column($recorrectArr1, 'le_id');
//                $recorrectArr2 = $conn->fetchAll("SELECT DISTINCT(hr_le_id) as le_id FROM homework_revise_sign_list where hr_co_id = {$coll['co_id']} and IFNULL(hr_te_image, '') <> '' and hr_le_id in ({$taskIds})");
//                $recorrectArr2 = array_column($recorrectArr2, 'le_id');
//                $recorrectArr = array_unique(array_merge($recorrectArr1, $recorrectArr2));
//                $tchInfo[$tchId]['taskRecorrectNum'] += count($recorrectArr);
//            }
//            catch (\Exception $e) {
//                continue;
//            }
//        }
//        //获取微课录制数
//        foreach ($tchInfo as $tchId => &$info) {
//            $examIdList = $conn->fetchAll("SELECT tk_tr_id FROM tk_power where tk_us_id = {$tchId}");
//            $examIdList = array_column($examIdList, 'tk_tr_id');
//            foreach ($examIdList as $examId) {
//                try {
//                    $dbExam = $dbName . '_exam' . $examId;
//                    $coursewareNum = $conn->fetchOne("select count(*) as count from {$dbExam}.list_courseware where li_us_id = {$tchId} and li_datetimes >= '{$startTime}' and li_datetimes < '{$endTime}'")['count'];
//                    $info['coursewareNum'] += $coursewareNum;
//                }
//                catch (\Exception $e) {
//                    continue;
//                }
//            }
//        }
//        return array_values($tchInfo);
//    }

    /**
     * 获取智通课堂2.0考核表所需统计信息
     *
     * @param $schoolId
     * @param $startTime
     * @param $endTime
     * @return array
     * @throws \Exception
     *
     * create by ck 20171025
     */
//    private function getZtClass2($schoolId, $startTime, $endTime)
//    {
//        $startTime = date('Y-m-d H:i:s', $startTime);
//        $endTime   = date('Y-m-d H:i:s', $endTime);
//        $dbName    = '';
//        $conn      = Main::getSchoolMainDB($schoolId, $dbName);
//        $conn->connect();
//        if (!$conn) {
//            throw new \Exception('数据库连接失败');
//        }
//        $tchInfo = [];
////        $collList = $conn->fetchAll("SELECT co_id, co_dates, group_concat(cl_id) as cl_ids, te_us_id, ( SELECT us_name FROM users WHERE us_id = te_us_id ) AS te_us_name, sy_name, at_qc_id FROM attendclass_time_class, teacher_list, course_list, class_list, system_type, users WHERE cl_at_id = at_id AND co_id = te_co_id AND te_us_id = us_id AND us_xk_flag = 0 AND te_flag = 0 AND cl_flag = 1 AND cl_id = te_cl_id AND co_coach_flag = 0 AND co_typeflag = 1 AND co_km_id = sy_id AND at_qc_id IN ( SELECT sy_id FROM system_type WHERE sy_type = 'kkqcsz' AND sy_state = 0 AND sy_name2 = 1 ) and co_status = 1 GROUP BY co_id, te_us_id ORDER BY co_ord");
//        $collList = $conn->fetchAll("SELECT co_id, co_dates, group_concat(cl_id) as cl_ids, te_us_id, ( SELECT us_name FROM users WHERE us_id = te_us_id ) AS te_us_name, sy_name, at_qc_id FROM attendclass_time_class, teacher_list, course_list, class_list, system_type, users WHERE cl_at_id = at_id AND co_id = te_co_id AND te_us_id = us_id AND us_xk_flag = 0 AND te_flag = 0 AND cl_flag = 1 AND cl_id = te_cl_id AND co_coach_flag = 0 AND co_typeflag = 1 AND co_km_id = sy_id AND at_qc_id IN ( SELECT sy_id FROM system_type WHERE sy_type = 'kkqcsz' AND sy_state = 0) and co_status = 1 GROUP BY co_id, te_us_id ORDER BY co_ord");
//        foreach ($collList as $coll) {
//            $tchId = $coll['te_us_id'];
//            if (!isset($tchInfo[$tchId])) {
//                $tchInfo[$tchId] = [
//                    'tchId'         => $tchId,
//                    'tchName'       => $coll['te_us_name'],
//                    'classList'     => [],
//                    'taskValidNum'  => 0
//                ];
//            }
//            $dbCourse = $dbName . '_course' . $coll['co_id'];
//
//            try {
//                //获取班级信息
////                $class = $conn->fetchOne("select cl_id as classId,cl_name as className from class_list where cl_id = {$coll['cl_id']}");
////                $stuNum = $conn->fetchOne("select count(*) as stuNum from students_list where st_cl_id = {$coll['cl_id']}")['stuNum'];
////                $tchInfo[$tchId]['classList'][] = array_merge($class, ['stuNum' => $stuNum, 'coId' => $coll['co_id']]);
//                $tchInfo[$tchId]['classList'] = $conn->fetchAll("select cl_id as classId,cl_name as className,cl_co_id as coId,count(st_us_id) as stuNum from class_list,students_list where cl_id = st_cl_id and cl_id in ({$coll['cl_ids']}) group by cl_id");
//
//                //获取有效课堂数
//                $taskValidNum = $conn->fetchOne("SELECT COUNT(DISTINCT(rm_id)) as count FROM {$dbCourse}.ztkt_answer LEFT JOIN (SELECT * FROM {$dbCourse}.ztkt_question LEFT JOIN (SELECT * FROM {$dbCourse}.ztkt_task LEFT JOIN {$dbCourse}.ztkt_room ON rm_id = ta_rm_id and rm_time >= '{$startTime}' and rm_time < '{$endTime}') B ON ta_id = qt_ta_id) A ON qt_id = as_qt_id")['count'];
//                $tchInfo[$tchId]['taskValidNum'] += $taskValidNum;
//            }
//            catch (\Exception $e) {
//                continue;
//            }
//        }
//        return array_values($tchInfo);
//    }

    /**
     * 获取英语刷题王所需统计信息
     *
     * @param $schoolId
     * @param $startTime
     * @param $endTime
     * @return array
     * @throws \Exception
     *
     * create by ck 20171025
     * modify by ck 20171130    更改布置份数计算方式
     * modify by ck 20180514    增加英刷3.0数据
     */
//    private function getEnglishBrush($schoolId, $startTime, $endTime)
//    {
//        $startTime = date('Y-m-d H:i:s', $startTime);
//        $endTime   = date('Y-m-d H:i:s', $endTime);
////        $dbName    = '';
////        $conn      = Main::getSchoolMainDB($schoolId, $dbName);
////        $conn->connect();
////        if (!$conn) {
////            throw new \Exception('数据库连接失败');
////        }
////        $classInfo = [];
////        $collList = $conn->fetchAll("SELECT co_id, co_dates, cl_id, te_us_id, ( SELECT us_name FROM users WHERE us_id = te_us_id ) AS te_us_name, sy_name, at_qc_id FROM attendclass_time_class, teacher_list, course_list, class_list, system_type, users WHERE cl_at_id = at_id AND co_id = te_co_id AND te_us_id = us_id AND us_xk_flag = 0 AND te_flag = 0 AND cl_flag = 1 AND cl_id = te_cl_id AND co_coach_flag = '12' AND co_typeflag = 1 AND co_km_id = sy_id AND at_qc_id IN ( SELECT sy_id FROM system_type WHERE sy_type = 'kkqcsz' AND sy_state = 0 AND sy_name2 = 1 ) and co_status = 1 GROUP BY co_id, cl_id ORDER BY co_ord");
////        $collList = $conn->fetchAll("SELECT co_id, co_dates, cl_id, te_us_id, ( SELECT us_name FROM users WHERE us_id = te_us_id ) AS te_us_name, sy_name, at_qc_id FROM attendclass_time_class, teacher_list, course_list, class_list, system_type, users WHERE cl_at_id = at_id AND co_id = te_co_id AND te_us_id = us_id AND us_xk_flag = 0 AND te_flag = 0 AND cl_flag = 1 AND cl_id = te_cl_id AND co_coach_flag = '12' AND co_typeflag = 1 AND co_km_id = sy_id AND at_qc_id IN ( SELECT sy_id FROM system_type WHERE sy_type = 'kkqcsz' AND sy_state = 0) and co_status = 1 GROUP BY co_id, cl_id ORDER BY co_ord");
////        foreach ($collList as $coll) {
////            $classId  = $coll['cl_id'];
////            $classKey = $coll['co_id'] . '-' . $classId;
////
////            try {
////                if (!isset($classInfo[$classKey])) {
////                    //获取班级信息
////                    $className  = $conn->fetchOne("select cl_name as className from class_list where cl_id = {$coll['cl_id']}")['className'];
////                    $stuNum     = $conn->fetchOne("select count(*) as stuNum from students_list where st_cl_id = {$coll['cl_id']}")['stuNum'];
////                    $classInfo[$classKey] = [
////                        'classId'       => $classId,
////                        'className'     => $className,
////                        'stuNum'        => $stuNum,
////                        'tchId'         => $coll['te_us_id'],
////                        'tchName'       => $coll['te_us_name'],
////                        'coId'          => $coll['co_id'],
////                        'practiceNum'   => 0,
////                        'taskFixNum'    => 0,
////                        'taskStuNum'    => 0,
////                        'taskUploadNum' => 0
////                    ];
////                }
////                $dbCourse = $dbName . '_course' . $coll['co_id'];
////
////                //获取自练次数
////                $practiceNum = $conn->fetchOne("select count(*) as count from {$dbCourse}.yystw_studentchapter where sc_mta_id =0 and sc_st_cl_id={$classId} and sc_finishtime >= '{$startTime}' and sc_finishtime < '{$endTime}'")['count'];
////                $classInfo[$classKey]['practiceNum'] += $practiceNum;
////
////                //获取布置次数
////                $fixList = $conn->fetchAll("select mta_id as taskId,mta_stucount as fixNum,mta_cl_ids as classIds from {$dbCourse}.yystw_maintask where mta_delete=0 and mta_cl_ids like '%{$classId}%' and mta_ctime >= '{$startTime}' and mta_ctime < '{$endTime}'");
////                $taskIds = [];
////                foreach ($fixList as $fix) {
////                    if (!in_array($classId, explode(',', $fix['classIds']))) {
////                        continue;
////                    }
////                    $taskIds[] = $fix['taskId'];
////                    $classInfo[$classKey]['taskFixNum']++;
//////                    $classInfo[$classKey]['taskStuNum'] += $fix['fixNum'];
////                }
////
////                if (!$taskIds) {
////                    continue;
////                }
////                $taskIds   = implode(',', $taskIds);
////
////                //获取布置份数
////                $taskStuNum = $conn->fetchOne("select count(*) as count from {$dbCourse}.yystw_submitstudent where ss_cl_id = '{$classId}' and ss_delete=0 and ss_redo=0 and ss_mta_id in ({$taskIds})")['count'];
////                $classInfo[$classKey]['taskStuNum'] += $taskStuNum;
////
////                //获取上交份数
////                $uploadNum = $conn->fetchOne("select count(*) as count from {$dbCourse}.yystw_submitstudent where ss_cl_id = '{$classId}' and ss_status=1 and ss_delete=0 and ss_redo=0 and ss_mta_id in ({$taskIds})")['count'];
////                $classInfo[$classKey]['taskUploadNum'] += $uploadNum;
////            }
////            catch (\Exception $e) {
////                continue;
////            }
////        }
////        return array_values($classInfo);
//
//        //获取刷题3.0数据
//        $classInfo3 = $this->getBrushInfo3($schoolId, $startTime, $endTime, 3);
//        return array_values($classInfo3);
////        return array_values(array_merge($classInfo, $classInfo3));
//    }

    /**
     * 获取数学刷题王所需统计信息
     *
     * @param $schoolId
     * @param $startTime
     * @param $endTime
     * @param int $benefitScore
     * @param int $appFlag
     * @return array
     * @throws \Exception
     *
     * create by ck 20171026
     * modify by ck 20171114    更改自练次数为自练题数
     * modify by ck 20180504    去除2.0数据
     */
//    private function getMathBrush($schoolId, $startTime, $endTime, $benefitScore = 15, $appFlag = 11)
//    {
////        $startTime = date('Y-m-d H:i:s', $startTime);
////        $endTime   = date('Y-m-d H:i:s', $endTime);
////        return $this->getBrushInfo3($schoolId, $startTime, $endTime, $appFlag - 9);
//
//        $startTime = date('Y-m-d H:i:s', $startTime);
//        $endTime   = date('Y-m-d H:i:s', $endTime);
////        $dbName    = '';
////        $conn      = Main::getSchoolMainDB($schoolId, $dbName);
////        $conn->connect();
////        if (!$conn) {
////            throw new \Exception('数据库连接失败');
////        }
////        $classInfo = [];
////        $collList = $conn->fetchAll("SELECT co_id, co_dates, cl_id, te_us_id, ( SELECT us_name FROM users WHERE us_id = te_us_id ) AS te_us_name, sy_name, at_qc_id FROM attendclass_time_class, teacher_list, course_list, class_list, system_type, users WHERE cl_at_id = at_id AND co_id = te_co_id AND te_us_id = us_id AND us_xk_flag = 0 AND te_flag = 0 AND cl_flag = 1 AND cl_id = te_cl_id AND co_coach_flag = '{$appFlag}' AND co_typeflag = 1 AND co_km_id = sy_id AND at_qc_id IN ( SELECT sy_id FROM system_type WHERE sy_type = 'kkqcsz' AND sy_state = 0 AND sy_name2 = 1 )  and co_status = 1 GROUP BY co_id, cl_id ORDER BY co_ord");
////        $collList = $conn->fetchAll("SELECT co_id, co_dates, cl_id, te_us_id, ( SELECT us_name FROM users WHERE us_id = te_us_id ) AS te_us_name, sy_name, at_qc_id FROM attendclass_time_class, teacher_list, course_list, class_list, system_type, users WHERE cl_at_id = at_id AND co_id = te_co_id AND te_us_id = us_id AND us_xk_flag = 0 AND te_flag = 0 AND cl_flag = 1 AND cl_id = te_cl_id AND co_coach_flag = '{$appFlag}' AND co_typeflag = 1 AND co_km_id = sy_id AND at_qc_id IN ( SELECT sy_id FROM system_type WHERE sy_type = 'kkqcsz' AND sy_state = 0)  and co_status = 1 GROUP BY co_id, cl_id ORDER BY co_ord");
////        foreach ($collList as $coll) {
////            $classId  = $coll['cl_id'];
////            $classKey = $coll['co_id'] . '-' . $classId;
////
////            try {
////                if (!isset($classInfo[$classKey])) {
////                    //获取班级信息
////                    $className  = $conn->fetchOne("select cl_name as className from class_list where cl_id = {$coll['cl_id']}")['className'];
////                    $stuNum     = $conn->fetchOne("select count(*) as stuNum from students_list where st_cl_id = {$coll['cl_id']}")['stuNum'];
////                    $classInfo[$classKey] = [
////                        'classId'       => $classId,
////                        'className'     => $className,
////                        'stuNum'        => $stuNum,
////                        'tchId'         => $coll['te_us_id'],
////                        'tchName'       => $coll['te_us_name'],
////                        'coId'          => $coll['co_id'],
////                        'practiceNum'   => 0,
////                        'taskFixNum'    => 0,
////                        'taskStuNum'    => 0,
////                        'taskUploadNum' => 0
////                    ];
////                }
////                $dbCourse = $dbName . '_course' . $coll['co_id'];
////
////                //获取自练题量
//////                $practiceNum = $conn->fetchOne("SELECT count(*) as count FROM {$dbCourse}.st_upload LEFT JOIN {$dbCourse}.st_student on up_us_id = su_us_id where up_as_id = 0 and up_type <> 5 and su_cl_id = {$classId} and su_benefit_score >= {$benefitScore} and up_date >= '{$startTime}' and up_date < '{$endTime}'")['count'];
////                $practiceNum = $conn->fetchOne("select count(*) as count from {$dbCourse}.st_upload_content left join {$dbCourse}.st_student on su_us_id = uc_us_id where su_cl_id = '{$classId}' and uc_date >= '{$startTime}' and uc_date < '{$endTime}' and su_benefit_score >= {$benefitScore}")['count'];
////                $classInfo[$classKey]['practiceNum'] += $practiceNum;
////
////                //获取布置次数
////                $taskFixNum = $conn->fetchOne("SELECT sum(as_num) as count FROM {$dbCourse}.st_assign_info where as_cl_id = {$classId} and as_date >= '{$startTime}' and as_date < '{$endTime}'")['count'];
////                $classInfo[$classKey]['taskFixNum'] += $taskFixNum;
////
////                //获取布置份数
////                $taskStuNum = $conn->fetchOne("select count(*) as count from {$dbCourse}.st_assign_obj LEFT JOIN {$dbCourse}.st_assign_info on as_id = ao_as_id where as_cl_id = {$classId} and as_date >= '{$startTime}' and as_date < '{$endTime}'")['count'];
////                $classInfo[$classKey]['taskStuNum'] += $taskStuNum;
////
////                //获取上交份数
////                $taskUploadNum = $conn->fetchOne("select count(*) as count from {$dbCourse}.st_upload where up_ao_id in (select ao_id from {$dbCourse}.st_assign_obj LEFT JOIN {$dbCourse}.st_assign_info on as_id = ao_as_id where as_cl_id = {$classId} and as_date >= '{$startTime}' and as_date < '{$endTime}')")['count'];
////                $classInfo[$classKey]['taskUploadNum'] += $taskUploadNum;
////            }
////            catch (\Exception $e) {
////                continue;
////            }
////        }
//
//        //获取刷题3.0数据
//        $classInfo3 = $this->getBrushInfo3($schoolId, $startTime, $endTime, $appFlag - 9);
//        return array_values($classInfo3);
////        return array_values(array_merge($classInfo, $classInfo3));
//    }

    /**
     * 获取科学刷题王所需统计信息
     *
     * @param $schoolId
     * @param $startTime
     * @param $endTime
     * @param int $benefitScore
     * @return array
     * @throws \Exception
     *
     * create by ck 20171026
     */
//    private function getScienceBrush($schoolId, $startTime, $endTime, $benefitScore = 15)
//    {
//        return $this->getMathBrush($schoolId, $startTime, $endTime, $benefitScore, 13);
//    }

    /**
     * 获取古文刷题王所需统计信息
     *
     * @param $schoolId
     * @param $startTime
     * @param $endTime
     * @return array
     *
     * create by ck 20171028
     */
//    private function getChineseBrush($schoolId, $startTime, $endTime)
//    {
//        $chineseBrush = [];
//        $result = $this->getHttpResult(
//            'CA101004',
//            'statistics/getSingleSchInfo',
//            ['schoolId' => $schoolId, 'startTime' => $startTime, 'endTime' => $endTime]
//        );
//        foreach ($result as $row) {
//            $chineseBrush[] = [
//                'classId'       => $row['classId'],
//                'className'     => $row['className'],
//                'stuNum'        => $row['stuNum'],
//                'tchId'         => $row['tchId'],
//                'tchName'       => $row['tchName'],
//                'practiceNum'   => $row['practiceNum'],
//                'taskFixNum'    => $row['taskFixNum'],
//                'taskStuNum'    => $row['stuNum'] * $row['taskFixNum'],
////                'taskStuNum'    => $row[''],
//                'taskUploadNum' => $row['taskUploadNum'],
//            ];
//        }
//        return $chineseBrush;
//    }

    /**
     * 获取口语训练所需统计信息
     *
     * @param $schoolId
     * @param $startTime
     * @param $endTime
     * @return array
     *
     * create by ck 20171028
     */
    private function getSpeakTrain($schoolId, $startTime, $endTime)
    {
        $speakTrain = [];
        $result = $this->getHttpResultWithKZ(
            '1500',
            '/static/getSingleSchInfo',
            ['iSchoolId' => $schoolId, 'iStartTime' => $startTime, 'iEndTime' => $endTime]
        );
        foreach ($result as $row) {
            $speakTrain[] = [
                'classId'   => $row['sClassId'],
                'className' => $row['sClassName'],
                'stuNum'    => $row['iStuNum'],
                'tchId'     => $row['iTchId'],
                'tchName'   => $row['sTchName'],
                'taskFixNum'=> $row['iTaskFixNum'],
                'clazz'     => $row['clazz'],
            ];
        }
        return $speakTrain;
    }

    /**
     * 获取语文基础知识所需统计信息
     *
     * @param $schoolId
     * @param $startTime
     * @param $endTime
     * @return array
     *
     * create by ck 20171028
     */
    private function getChineseBasic($schoolId, $startTime, $endTime)
    {
        $chineseBasic = [];
        $result = $this->getHttpResult(
            'CA101009',
            '/static/getSingleSchInfo',
            ['schoolId' => $schoolId, 'startTime' => $startTime, 'endTime' => $endTime]
        );
        foreach ($result as $row) {
            $chineseBasic[] = [
                'classId'   => $row['classId'],
                'className' => $row['className'],
                'stuNum'    => $row['stuNum'],
                'tchId'     => $row['tchId'],
                'tchName'   => $row['tchName'],
                'taskFixNum'=> $row['taskFixNum'],
                'clazz'     => $row['clazz'],
            ];
        }
        return $chineseBasic;
    }

    /**
     * 获取刷题王3.0考核数据
     *
     * @param $schoolId
     * @param $startTime
     * @param $endTime
     * @param $type         --学科类型（2=数学，4=科学）
     * @return mixed
     * @throws \Exception
     *
     * create by ck 20180327
     * modify by ck 20180404    自练题数*10
     * modify by ck 20180629    英语取消自联*10
     */
//    private function getBrushInfo3($schoolId, $startTime, $endTime, $type)
//    {
//        $startTime = strtotime($startTime);
//        $endTime   = strtotime($endTime);
//        $time= microtime(true);
//        $url = Main::getConfigByName('bigData')['url'];
//        if (!$url) {
//            throw new \Exception('bigData配置地址不存在！');
//        }
//        $httpClient = new HttpClient($url);
//        $response   = $httpClient->get(sprintf('/bigdata/product_stw/subject/%d/getKpiInfo', $type), [
//            'schoolId'  => $schoolId,
//            'startTime' => $startTime,
//            'endTime'   => $endTime
//        ]);
//        if (!$response->isSuccess()) {
//            throw new \Exception('请求失败：' . json_encode($response, JSON_UNESCAPED_UNICODE));
//        }
//        $data = $response->toArray()['data'];
////        if (!$data) {
////            throw new \Exception('无数据');
////        }
//        if ($type != 3) {
//            foreach ($data as &$row) {
//                $row['practiceNum'] *= 10;
//            }
//            unset($row);
//        }
//
//        $this->devInfo['Brush_' . $type]['timeCost'] = microtime(true) - $time;
//        $this->devInfo['Brush_' . $type]['response'] = $data;
//        return $data;
//    }

    /**
     * http请求
     *
     * @param $configName
     * @param $path
     * @param $baseParams
     * @param array $extraParams
     * @return array|bool|mixed|\stdClass
     * @throws \Exception
     *
     * create by ck 20171026
     */
    private function getHttpResult($configName, $path, $baseParams, $extraParams = [])
    {
        $url = Main::getConfigByName('stats_' . $configName)['url'];
        if (!$url) {
            throw new \Exception($configName . '配置地址不存在！');
        }

        $this->httpClient->setBaseUrl($url)->setTimeout(180);
        $response = $this->httpClient->get($path, $baseParams + $extraParams);
        if (!$response->isSuccess()) {
            throw new \Exception($configName . '请求失败：' . json_encode($response, JSON_UNESCAPED_UNICODE));
        }
        $body = $response->toArray();
        if ($body === false) {
            throw new \Exception($configName . '请求失败：返回不正确：' . $response->body);
        }
        if (isset($body['error'])) {
            throw new \Exception($configName . '请求失败：' . $body['error']);
        }
        return $body ?: [];
    }

    /**
     * KZ形式http请求
     *
     * @param $configName
     * @param $path
     * @param $K
     * @return array
     * @throws \Exception
     *
     * create by ck 20171028
     */
    private function getHttpResultWithKZ($configName, $path, $K)
    {
        $url = Main::getConfigByName('stats_' . $configName)['url'];
        if (!$url) {
            throw new \Exception($configName . '配置地址不存在！');
        }

        $this->httpClient->setBaseUrl($url);
        $response = $this->httpClient->post($path, ['K' => json_encode($K, JSON_UNESCAPED_UNICODE), 'Z' => 0]);
        if (!$response->isSuccess()) {
            throw new \Exception($configName . '请求失败：' . json_encode($response, JSON_UNESCAPED_UNICODE));
        }
        $body = $response->toArray();
        if (!$body) {
            throw new \Exception($configName . '请求失败：返回不正确：' . $response->body);
        }
        if ($body['R'] != 200) {
            throw new \Exception($configName . '请求失败：' . $body['I']);
        }
        return json_decode(Tool::unZipData($body['D'], $body['Z']), true);
    }

    /**
     * 合并数据
     *
     * @param $array1
     * @param $array2
     *
     * create by ck 20171026
     */
//    private function mergeCommonInfo(&$array1, &$array2)
//    {
//        $array1 = @array_column($array1, null, 'tchId');
//        foreach ($array2 as $record) {
//            $tchId = $record['tchId'];
//            if (!isset($array1[$tchId])) {
//                $array1[$tchId] = $record;
//                continue;
//            }
//            foreach ($record as $key => $value) {
//                if (in_array($key, [
//                    'classList',
//                    'taskFixNum',
//                    'taskTopicNum',
//                    'taskStuNum',
//                    'taskUploadNum',
//                    'taskCorrectNum',
//                    'taskGroupNum',
//                    'taskWrongNum',
//                    'coursewareNum',
//                    'taskRecorrectNum',
//                    'taskValidNum'
//                ])) {
//                    $array1[$tchId][$key] += $value;
//                }
//            }
//        }
//        $array1 = array_values($array1);
//        unset($array2);
//    }

    /**
     * 过滤测试数据
     *
     * @param $rows
     * @param $schoolId
     *
     * create by ck 20171030
     * modify by ck 20180509    更改过滤条件
     */
    private function filterStatsRecord(&$rows, $schoolId)
    {
//        static $tchIds = [], $first = true;
//        if ($first)
//            $first = false;
//            $tchIds = XhsysUser::find([
//                'columns'    => 'iUserId',
//                'conditions' => '(bCompany = 1 OR bDisable = 1 OR bHistory = 1) AND iUserType = 4 AND iSchoolId = :schoolId:',
//                'bind'       => ['schoolId' => $schoolId]
//            ])->toArray();
//            $tchIds = array_column($tchIds, 'iUserId');
//        }
        if (!$this->tchIds) {
            $this->tchIds = array_keys($this->getTchInfo($schoolId));
        }
        foreach ($rows as $index => $row) {
//            if (isset($row['tchId']) && in_array($row['tchId'], $tchIds)) {
            if (isset($row['tchId']) && !in_array($row['tchId'], $this->tchIds)) {
                unset($rows[$index]);
                continue;
            }
            if (isset($row['classList'])) {
                foreach ($row['classList'] as $class) {
                    if (strpos($class['className'], '测试') !== false || ($schoolId != 4194 && strpos($class['className'], '00') !== false)){
                        unset($rows[$index]);
                        continue 2;
                    }
                }
            }
            if (isset($row['tchName']) && !$row['tchName']) {
                unset($rows[$index]);
                continue;
            }
            if (isset($row['className']) && (strpos($row['className'], '测试') !== false || ($schoolId != 4194 && strpos($row['className'], '00') !== false))){
                unset($rows[$index]);
                continue;
            }
        }
    }

    /**
     * 合并班级为单位的数据
     *
     * @param $rows
     *
     * create by ck 20180426
     * modify by ck 20180509    处理班级id
     */
    private function mergeClassInfo(&$rows)
    {
//        $result = [];
//        foreach ($rows as $row) {
//            $classId = $row['classId'];
//            if (!isset($result[$classId])) {
//                $result[$classId] = $row;
//                $result[$classId]['tchId'] = [$row['tchId']];
//                continue;
//            }
//            foreach ($row as $key => $value) {
//                switch ($key) {
//                    case 'classId':
//                    case 'className':
//                    case 'stuNum': break;
//                    case 'tchId': $result[$classId][$key][] = $value; break;
//                    case 'tchName': $result[$classId][$key] .= ('、' . $value); break;
//                    default: $result[$classId][$key] += $value;
//                }
//            }
//        }
//        $rows = array_values($result);
        foreach ($rows as &$row) {
            $row['clazzId'] = $row['classId'];
            $row['classId'].= '_' . $row['tchId'];
        }
    }

    /**
     * 处理云作业id相同班级
     *
     * @param $arr
     *
     * create by ck 20171226
     */
    private function dealClassList(&$arr)
    {
        foreach ($arr as $index => $obj) {
            $arr[$index]['classList'] = array_values(array_column($obj['classList'], null, 'classId'));
        }
    }

    private function division($a, $b, $precision = 1)
    {
        if ($b == 0) {
            return 0;
        }
        return @round($a / $b, $precision);
    }

    private function dealRound($val, $precision = 1) {
        if (is_nan($val)) {
            $val = 0;
        }
        $val = @round($val, $precision);
        return $val;
    }
}
